from requests.exceptions import RequestException
from api.api import Api
from utils.config import PARAMETER_LIST_TEMPLATE, PARAMETER_DELETE_TEMPLATE
from utils.log_util import logger
from utils.time import get_dates
import time


def retry_api_call(func, max_retries=3, initial_delay=1):
    """优化后的重试机制，使用指数退避算法，增加JSON解析错误处理"""
    last_error = None
    for attempt in range(max_retries + 1):
        try:
            response = func()
            if response.status_code == 200:
                try:
                    response.json()
                    return response
                except ValueError as e:
                    last_error = f"JSON解析失败: {str(e)} | 响应内容: {response.text[:200]}"
                    continue
            last_error = f"HTTP状态码异常: {response.status_code}"
        except RequestException as e:
            last_error = f"请求失败: {str(e)}"
        except Exception as e:
            raise
        if attempt < max_retries:
            delay = initial_delay * (2 ** attempt)
            logger.debug(f"请求失败，第{attempt + 1}次重试（共{max_retries}次），等待{delay:.1f}秒")
            time.sleep(delay)
    logger.error(f"请求最终失败: {last_error}")
    return None


def gly_list(app_id, entry_id, fields, months_back=1, chunk_size=100, limit=2000):
    """列表处理函数"""
    try:
        parameter_list = {
            **PARAMETER_LIST_TEMPLATE,
            'app_id': app_id,
            'entry_id': entry_id,
            'limit': limit
        }
        if fields != 'None':
            parameter_list['filter'] = {
                'rel': 'and',
                'cond': [{
                    'field': fields,
                    'type': 'datetime',
                    'method': 'range',
                    'value': get_dates(months_back)
                }]
            }
        parameter_delete = {
            **PARAMETER_DELETE_TEMPLATE,
            'app_id': app_id,
            'entry_id': entry_id
        }
        logger.debug(f"参数初始化完成 | 表单ID: {parameter_list}")
        total_deleted = 0
        batch_counter = 1
        while True:
            list_response = retry_api_call(lambda: Api().list(parameter_list))
            if not list_response:
                return 500
            try:
                data = list_response.json().get('data', [])
            except ValueError:
                logger.error(f"列表响应JSON解析失败 | 响应内容: {list_response.text[:200]}")
                return 500
            if not data:
                break
            data_ids = [item['_id'] for item in data]
            for i in range(0, len(data_ids), chunk_size):
                chunk = data_ids[i:i + chunk_size]
                delete_response = retry_api_call(
                    lambda: Api().delete({**parameter_delete, 'data_ids': chunk})
                )
                if not delete_response:
                    return 500
                try:
                    result = delete_response.json()
                    success = result.get('success_count', 0)
                    total_deleted += success
                    logger.info(
                        f" 批次 {batch_counter} | 累计删除: {success}/{total_deleted}"
                    )
                    batch_counter += 1
                except ValueError:
                    logger.error(f"删除响应JSON解析失败 | 响应内容: {delete_response.text[:200]}")
                    return 500

        logger.info(f"任务完成 | 表单ID:{entry_id} | 总删除量: {total_deleted}")
        return 200


    except (KeyError, IndexError) as e:
        logger.error(f"数据处理出错: {str(e)}")
        return 500
    except RequestException as e:
        logger.error(f"API请求出错: {str(e)}")
        return 500